<?php
require "../../../ajax/config/config.inc.php";

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = addslashes($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

if ( isset ( $_POST['cmdAdd']) && $_POST['cmdAdd'] != '' ) {
	$rsSettingsExist = mysql_query("SELECT * FROM settings WHERE settings_name = '".addslashes(trim($_POST['settings_name']))."'");
	$rownum_rsSettingsExists = mysql_num_rows($rsSettingsExist);
	if ($rownum_rsSettingsExists == 0) {
		$insertSQL = sprintf("INSERT INTO settings (settings_name, settings_value) VALUES (%s,%s)",GetSQLValueString($_POST['settings_name'], "text"),GetSQLValueString($_POST['settings_value'], "text"));
		$Result1 = mysql_query($insertSQL) or die(mysql_error());
	} 
	else {
		echo "<script>alert('Settings Name already Exists.')</script>";
	}
}
if ( isset ( $_POST['cmdUpdate']) && $_POST['cmdUpdate'] != '' ) {
	$currency_array = array();
	$currency_array = explode("|",$_POST['settings_array']);
	foreach($currency_array as $key => $value) {
		if ((isset($_POST['settings_name_'.$value]) && $_POST['settings_name_'.$value] != "") && (isset($_POST['settings_value_'.$value]) && $_POST['settings_value_'.$value] != "")) {
			$updateSQL = sprintf("UPDATE settings SET settings_name=%s, settings_value=%s WHERE id=%s",
				GetSQLValueString($_POST['settings_name_'.$value], "text"), 
				GetSQLValueString($_POST['settings_value_'.$value], "text"), 
				GetSQLValueString($value, "int"));
  			$Result2 = mysql_query($updateSQL) or die(mysql_error());
		}
	}
} 
else if ( isset ( $_POST['cmdDelete']) && $_POST['cmdDelete'] != '' ) { //save operation
	for ( $cnt = 0; $cnt < sizeof($_POST["rec_id"]) ; $cnt ++ ) {
		if (isset($_POST["rec_id"][$cnt]) && $_POST["rec_id"][$cnt] != '' && $_POST["rec_id"][$cnt] != 'on') {
			$ids .= $_POST["rec_id"][$cnt];
			if ($cnt < sizeof($_POST["rec_id"]) - 1) {
				$ids .= ',';
			}
		}
	}
	if (is_array($_POST["rec_id"])){
		header('Location: settings_delete.php?id='.$ids) ;
	}
}
else if (isset ( $_POST['cmdSearch']) && $_POST['cmdSearch'] != '' && isset($_POST['search'])) {
	$param_search = " AND (settings_name LIKE '".addslashes($_POST['search'])."%' OR settings_name LIKE '%".addslashes($_POST['search'])."%') ";
}

$maxRows_rsSettings = 10;
$pageNum_rsSettings = 0;
if (isset($_GET['pageNum_rsSettings'])) {
  $pageNum_rsSettings = $_GET['pageNum_rsSettings'];
}
$startRow_rsSettings = $pageNum_rsSettings * $maxRows_rsSettings;
$param_rsSettings = " WHERE 1=1 ".$param_search;

//$query_rsSettings = sprintf("select * from rooms %s ORDER BY door_name %s", $param_rsSettings, $sortDate);
$query_rsSettings = sprintf("select * from settings %s ", $param_rsSettings);
$query_limit_rsSettings = sprintf("%s LIMIT %d, %d", $query_rsSettings, $startRow_rsSettings, $maxRows_rsSettings);
$rsSettings = mysql_query($query_limit_rsSettings) or die(mysql_error());
$row_rsSettings = mysql_fetch_assoc($rsSettings);

if (isset($_GET['totalRows_rsSettings'])) {
  $totalRows_rsSettings = $_GET['totalRows_rsSettings'];
} else {
  $all_rsSettings = mysql_query($query_rsSettings);
  $totalRows_rsSettings = mysql_num_rows($all_rsSettings);
}
$totalPages_rsSettings = ceil($totalRows_rsSettings/$maxRows_rsSettings)-1;

$queryString_rsSettings = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_rsSettings") == false && 
        stristr($param, "totalRows_rsSettings") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_rsSettings = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_rsSettings = sprintf("&totalRows_rsSettings=%d%s", $totalRows_rsSettings, $queryString_rsSettings);

$TFM_LimitLinksEndCount = 9;
$TFM_temp = $pageNum_rsSettings + 1;
$TFM_startLink = max(1,$TFM_temp - intval($TFM_LimitLinksEndCount/2));
$TFM_temp = $TFM_startLink + $TFM_LimitLinksEndCount - 1;
$TFM_endLink = min($TFM_temp, $totalPages_rsSettings + 1);
if($TFM_endLink != $TFM_temp) $TFM_startLink = max(1,$TFM_endLink - $TFM_LimitLinksEndCount + 1);

?>
<html>
<head>
<title>Configuration</title>
<script type="text/javascript" src="../../../js/custom.js"></script>

<link href="../../../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>

<form name="form1" method="post" action="settings.php">
<table width="80%" border="0" align="center" cellpadding="3" cellspacing="2">
            <?php if (isset($_REQUEST['strMsg']) && $_REQUEST['strMsg'] != '') { ?>
            <tr>
              <td valign="middle"><div class="prompt" style="color:#009900; font-size:12px;"><?php echo $_REQUEST['strMsg'] ; ?></div></td>
            </tr>
            <?php } ?>
            <tr>
              <td valign="top" ><div style="float:left; width:30%"><p><font style="font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold; color:#678197;">CONFIGURATION</font></p>
              </div><div style="float:left; width:70%;"><p align="right"><font style="font:13px Arial,Verdana,  Helvetica, sans-serif; color:#666666">Settings:</font>&nbsp;<input type"text" name="search" id="search" class="textbox-search-style">&nbsp;<input name="cmdSearch" type="submit" id="cmdSearch" value="Search" class="buttons" style="width:70px;" />&nbsp;<input name="cmdAdd" type="submit" class="buttons" id="cmdAdd" style="width:70px;" value="Add New" />&nbsp;<input name="cmdUpdate" type="submit" id="cmdUpdate" value="Update" class="buttons" style="width:70px;" />&nbsp;<input name="cmdDelete" type="submit" id="cmdDelete" onClick="GP_popupConfirmMsg('You are about to delete a record(s). Are you sure you want to continue?');return document.MM_returnValue" value="Delete Checked Items" class="buttons" /></p></div></td>
			</td>
            </tr>
            <tr>
              <td><table width="100%" border="0" cellspacing="0" cellpadding="4" class="tablesorter">
				<thead>
                <tr class="bgHeader">
                  <td align="center" valign="top" width="4%"><input name="rec_id[]" type="checkbox" class="options" id="rec_id[]" onClick="toggleChecked(this)"></td>
                  <td align="left" valign="middle" width="4%"><strong style="color:#678197;">ID</strong></td>
				  <td align="left" width="46%"><strong style="color:#678197;">Settings</strong></td>
				   <td align="left" width="46%"><strong style="color:#678197;">Value</strong></td>
                </tr></thead>
                <?php
					$settingsArray = ""; 
					if ($totalRows_rsSettings > 0) { $bgNumber = 1; // Show if recordset not empty ?>
                <?php do { 
					$bgNumber++; 
					$bgResult = $bgNumber % 2;
					$settingsArray .= $row_rsSettings['id']."|";
				?>
                <tr <?php if ($bgResult > 0) echo 'bgcolor="#FAFAFA"';
					else echo "bgcolor=#F8FFFF"?>>
                  <td align="center" valign="top" class="divider"><input name="rec_id[]" type="checkbox" class="options" id="rec_id[]" onClick="toggleController(this)" value="<?php echo $row_rsSettings['id']; ?>"></td>
                  <td align="left"><?php echo $row_rsSettings['id']; ?></td>
				  <td align="left"><input type="text" name="settings_name_<?=$row_rsSettings['id']?>" value="<?php echo $row_rsSettings['settings_name']; ?>" class="textbox-style-2"></td>
				  <td align="left"><input type="text" name="settings_value_<?=$row_rsSettings['id']?>" value="<?php echo $row_rsSettings['settings_value']; ?>" class="textbox-style-2" ></td>
                </tr>
                <?php } while ($row_rsSettings = mysql_fetch_assoc($rsSettings)); ?>
                <?php } // Show if recordset not empty ?>
				<tr><td>&nbsp;</td><td><input type="hidden" name="settings_array" value="<?=substr($settingsArray,0,-1)?>">&nbsp;</td><td><input name="settings_name" id="settings_name" type="text" class="textbox-style-2" ><script>document.getElementById('settings_name').focus()</script></td>
				  <td><input name="settings_value" id="settings_value" type="text" class="textbox-style-2" ></td>
				</tr>
              </table></td>
            </tr>
			<tr><td colspan="4">&nbsp;</td></tr>
            <?php if ($totalRows_rsSettings > 0) { // Show if recordset not empty ?>
            <tr>
              <td align="right" valign="middle"><?php if ($pageNum_rsSettings > 0) { // Show if not first page ?>
                <a href="<?php printf("%s?pageNum_rsSettings=%d%s", $currentPage, 0, $queryString_rsSettings); ?>"><strong><<</strong> First</a> <a href="<?php printf("%s?pageNum_rsSettings=%d%s", $currentPage, max(0, $pageNum_rsSettings - 1), $queryString_rsSettings); ?>"><strong><</strong> Prev</a>
                <?php } // Show if not first page ?>
                <?php
for ($i = $TFM_startLink; $i <= $TFM_endLink; $i++) {
  $TFM_LimitPageEndCount = $i -1;
  if($TFM_LimitPageEndCount != $pageNum_rsSettings) {
    printf('<a href="'."%s?pageNum_rsSettings=%d%s", $currentPage, $TFM_LimitPageEndCount, $queryString_rsSettings.'">');
    echo "$i</a>";
  }else{
    echo "[<b>$i</b>]";
  }
if($i != $TFM_endLink) echo("&nbsp;");}
?>
                <?php if ($pageNum_rsSettings < $totalPages_rsSettings) { // Show if not last page ?>
                <a href="<?php printf("%s?pageNum_rsSettings=%d%s", $currentPage, min($totalPages_rsSettings, $pageNum_rsSettings + 1), $queryString_rsSettings); ?>">Next <strong>></strong></a> <a href="<?php printf("%s?pageNum_rsSettings=%d%s", $currentPage, $totalPages_rsSettings, $queryString_rsSettings); ?>">Last <strong>>></strong></a>
                <?php } // Show if not last page ?> </td>
            </tr>
            <?php } // Show if recordset not empty ?>
            <?php if ($totalRows_rsSettings == 0) { // Show if recordset empty ?>
            <tr>
                <td height="55" align="center" valign="middle"><strong style="color:#FF0000;">No record found. </strong></td>
            </tr>
            <?php } // Show if recordset empty ?>
          </table>
</form>
</body>
</head>
</html>